package com.icoolkj.ms.common.core.utils;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author icoolkj
 * @version 1.0
 * @description IP工具
 * @createDate 2025/02/10 19:20
 */
public class IpUtil {

    private static final String UNKNOWN = "unknown";

    /**
     * 得到用户的真实IP地址,如果有多个就取第一个
     *
     * @param request HttpServletRequest
     * @return 用户的真实IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        if (request == null) {
            return UNKNOWN;
        }

        String ip = request.getHeader("x-forwarded-for");

        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 有可能返回多个IP，取第一个
        String[] ips = ip.split(",");
        return ips[0].trim();
    }

    /**
     * 获取当前请求的IP地址
     *
     * @return 当前请求的IP地址
     */
    public static String getCurrentRequestIp() {
        if (RequestContextHolder.getRequestAttributes() == null) {
            return UNKNOWN;
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return getIpAddr(request);
    }
}
